﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        private Socket socketSend;
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //创建通信对象
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServerIP.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));

                //获取连接的远程服务器IP地址和端口
                socketSend.Connect(point);
                ShowMessage("连接" + ip + ":" + txtPort.Text + "成功！");

                //开启新线程，一直接收服务端发来的消息
                Thread thread = new Thread(Receive);
                thread.IsBackground = true;
                thread.Start();
            }
            catch 
            {
                MessageBox.Show("网络连接错误，请重试");
            }
        }
        private void ShowMessage(string msgStr)
        {
            txtNews.AppendText(msgStr + "\r\n");
        }

        /// <summary>
        /// 一直接收服务端的消息
        /// </summary>
        private void Receive()
        {
            try
            {
                //转换传入的参数类型
                while (true)
                {
                    //每2m内截取一单位
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    //实际接收的有效字节数
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    //把二进制内容转换成字符串显示到UI
                    //表示发送文字
                    if (buffer[0] == 0)
                    {
                        var str = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        ShowMessage("服务器:" + socketSend.RemoteEndPoint + ": " + str);
                    }
                    //表示发送文件
                    else if (buffer[0] == 1)
                    {
                        var dialog = new SaveFileDialog();
                        dialog.Title = "请选择保存的路径";
                        dialog.Filter= "文本文件 | *.txt | 图片 | *.jpg; *.png; *.gif; *.jpeg; *.bmp";
                        dialog.InitialDirectory = @"G:\Gitee\CsharpAdvanced\Client";
                        dialog.ShowDialog(this);

                        var path = dialog.FileName;
                        if (string.IsNullOrEmpty(path))
                        {
                            MessageBox.Show("请选择保存路径");
                            return;
                        }
                        using(FileStream fsWrite=new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 1, r - 1);
                        }
                        ShowMessage("服务器:" + socketSend.RemoteEndPoint + ": 给宁发了个文件");
                        
                    }
                    //表示发送震动
                    else if (buffer[0] == 2)
                    {
                        FormShake();
                    }
                    else
                    {
                        //其他
                    }
                }
            }
            catch 
            {

            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (socketSend == null || !socketSend.Connected)
            {
                MessageBox.Show("网络连接错误，请重新连入！");
                return;
            }
            var str = txtInput.Text;
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
            txtInput.Text = "";
        }
        private void FormShake()
        {
            int leftWidth = this.Left; //指定窗体左边值
            int topWidth = this.Top; //指定窗体上边值 

            for (int i = 0; i < 20; i++)
            {
                if (i % 2 == 0)
                {
                    this.Left = this.Left + 10;
                }
                else //否则 
                {
                    this.Left = this.Left - 10;
                }
                if (i % 2 == 0)
                {
                    this.Top = this.Top + 10;
                }
                else//否则 
                {
                    this.Top = this.Top - 10;
                }
                Thread.Sleep(30);//震动频率 
            }
            //重设窗体初此上边值
            this.Left = leftWidth;
            this.Top = topWidth; 
        }
    }
}
